<template>
  <el-config-provider :locale="zhCn">
    <div class="ai-thumbs-up-review">
      <!-- 动态背景 -->
      <div class="animated-background">
        <div class="floating-particles"></div>
        <div class="floating-particles"></div>
        <div class="floating-particles"></div>
      </div>

      <!-- 配置区域 -->
      <div class="config-container">
        <!-- AI点赞配置 -->
        <div class="config-section">
          <div class="section-header">
            <div class="section-title">
              <h2>点赞策略配置</h2>
            </div>
            <div class="section-toggle">
              <el-switch v-model="taskForm.isGood" :active-value="1" :inactive-value="2" :active-color="'#00ff88'" :inactive-color="'#2a2a2a'" size="large" />
            </div>
          </div>

          <div class="config-grid" :class="{ disabled: taskForm.isGood === 2 }">
            <div class="config-item">
              <div class="item-label">
                <span class="label-text">间隔天数</span>
                <span class="label-desc">下次点赞等待时间</span>
              </div>
              <div class="item-input">
                <el-input-number
                  v-model="taskForm.goodIntervalDay"
                  :min="1"
                  :max="365"
                  :disabled="taskForm.isGood === 2"
                  controls-position="right"
                  class="tech-input"
                />
                <span class="unit">天</span>
              </div>
            </div>

            <div class="config-item">
              <div class="item-label">
                <span class="label-text">延迟时间</span>
                <span class="label-desc">朋友圈发布后等待</span>
              </div>
              <div class="item-input">
                <el-input-number
                  v-model="taskForm.goodIntervalTime"
                  :min="1"
                  :max="1440"
                  :disabled="taskForm.isGood === 2"
                  controls-position="right"
                  class="tech-input"
                />
                <span class="unit">分钟</span>
              </div>
            </div>

            <div class="config-item">
              <div class="item-label">
                <span class="label-text">单友点赞数</span>
                <span class="label-desc">每个好友点赞条数</span>
              </div>
              <div class="item-input">
                <el-input-number
                  v-model="taskForm.goodNum"
                  :min="1"
                  :max="100"
                  :disabled="taskForm.isGood === 2"
                  controls-position="right"
                  class="tech-input"
                />
                <span class="unit">条</span>
              </div>
            </div>

            <div class="config-item">
              <div class="item-label">
                <span class="label-text">日点赞上限</span>
                <span class="label-desc">单日最大点赞数量</span>
              </div>
              <div class="item-input">
                <el-input-number
                  v-model="taskForm.goodSum"
                  :min="1"
                  :max="1000"
                  :disabled="taskForm.isGood === 2"
                  controls-position="right"
                  class="tech-input"
                />
                <span class="unit">条</span>
              </div>
            </div>

            <div class="config-item">
              <div class="item-label">
                <span class="label-text">随机点赞</span>
                <span class="label-desc">是否开启随机点赞</span>
              </div>
              <div class="item-input">
                <el-switch
                  v-model="taskForm.goodRandom"
                  :disabled="taskForm.isGood === 2"
                  class="tech-input"
                  :active-value="1"
                  :inactive-value="2"
                  :active-color="'#00ff88'"
                  :inactive-color="'#2a2a2a'"
                  size="large"
                />
              </div>
            </div>
          </div>
        </div>

        <!-- AI评论配置 -->
        <div class="config-section">
          <div class="section-header">
            <div class="section-title">
              <h2>评论策略配置</h2>
            </div>
            <div class="section-toggle">
              <el-switch
                v-model="taskForm.isComment"
                :active-value="1"
                :inactive-value="2"
                :active-color="'#00d4ff'"
                :inactive-color="'#2a2a2a'"
                size="large"
              />
            </div>
          </div>

          <div class="config-grid" :class="{ disabled: taskForm.isComment === 2 }">
            <div class="config-item">
              <div class="item-label">
                <span class="label-text">间隔天数</span>
                <span class="label-desc">下次评论等待时间</span>
              </div>
              <div class="item-input">
                <el-input-number
                  v-model="taskForm.commentIntervalDay"
                  :min="1"
                  :max="365"
                  :disabled="taskForm.isComment === 2"
                  controls-position="right"
                  class="tech-input"
                />
                <span class="unit">天</span>
              </div>
            </div>

            <div class="config-item">
              <div class="item-label">
                <span class="label-text">延迟时间</span>
                <span class="label-desc">朋友圈发布后等待</span>
              </div>
              <div class="item-input">
                <el-input-number
                  v-model="taskForm.commentIntervalTime"
                  :min="1"
                  :max="1440"
                  :disabled="taskForm.isComment === 2"
                  controls-position="right"
                  class="tech-input"
                />
                <span class="unit">分钟</span>
              </div>
            </div>

            <div class="config-item">
              <div class="item-label">
                <span class="label-text">单友评论数</span>
                <span class="label-desc">每个好友评论条数</span>
              </div>
              <div class="item-input">
                <el-input-number
                  v-model="taskForm.commentNum"
                  :min="1"
                  :max="100"
                  :disabled="taskForm.isComment === 2"
                  controls-position="right"
                  class="tech-input"
                />
                <span class="unit">条</span>
              </div>
            </div>

            <div class="config-item">
              <div class="item-label">
                <span class="label-text">日评论上限</span>
                <span class="label-desc">单日最大评论数量</span>
              </div>
              <div class="item-input">
                <el-input-number
                  v-model="taskForm.commentSum"
                  :min="1"
                  :max="1000"
                  :disabled="taskForm.isComment === 2"
                  controls-position="right"
                  class="tech-input"
                />
                <span class="unit">条</span>
              </div>
            </div>

            <div class="config-item">
              <div class="item-label">
                <span class="label-text">随机评论</span>
                <span class="label-desc">是否开启随机评论</span>
              </div>
              <div class="item-input">
                <el-switch
                  v-model="taskForm.commentRandom"
                  :disabled="taskForm.isComment === 2"
                  class="tech-input"
                  :active-value="1"
                  :inactive-value="2"
                  :active-color="'#00ff88'"
                  :inactive-color="'#2a2a2a'"
                  size="large"
                />
              </div>
            </div>
          </div>
        </div>

        <!-- 白名单配置 -->
        <div class="config-section">
          <div class="section-header">
            <div class="section-title">
              <h2>白名单配置</h2>
            </div>
          </div>

          <div class="config-grid">
            <div class="config-item friend-select-item">
              <div class="item-label">
                <span class="label-desc">仅对选中好友进行点赞评论</span>
              </div>
              <div class="item-content">
                <!-- 查询和操作区域 -->
                <div class="whitelist-management">
                  <div class="management-header">
                    <div class="search-area">
                      <el-input v-model="whitelistQuery.labIds" placeholder="标签ID" class="search-input" clearable />
                      <el-input v-model="whitelistQuery.name" placeholder="客户名称" class="search-input" clearable />
                      <el-button type="primary" @click="queryWhitelist" :loading="whitelistLoading" class="search-btn"> 查询 </el-button>
                    </div>
                    <div class="action-area">
                      <el-button type="success" @click="openFriendSelector('whitelist')" class="add-btn"> 添加好友 </el-button>
                      <el-button type="danger" @click="batchDeleteWhitelist" :disabled="whitelistSelectedIds.length === 0" class="delete-btn">
                        批量删除
                      </el-button>
                    </div>
                  </div>

                  <!-- 白名单列表 -->
                  <div class="whitelist-cards" v-if="whitelistData.length > 0 || whitelistQueried">
                    <div v-if="whitelistData.length === 0" class="empty-state">
                      <div class="empty-text">暂无白名单数据</div>
                    </div>
                    <div v-else class="cards-container">
                      <!-- 好友卡片列表 -->
                      <div class="friend-cards-grid">
                        <div
                          v-for="friend in whitelistData"
                          :key="friend.id"
                          class="friend-card"
                          :class="{ selected: whitelistSelectedIds.includes(friend.id.toString()) }"
                          @click="toggleWhitelistSelection(friend)"
                        >
                          <div class="card-content">
                            <div class="friend-avatar-container">
                              <img v-if="friend.customerUrl" :src="friend.customerUrl" class="friend-avatar" @error="handleImageError" />
                              <div v-else class="avatar-placeholder">
                                {{ (friend.customerName || '未知')[0] }}
                              </div>
                            </div>
                            <div class="friend-name">{{ friend.customerName || '未知好友' }}</div>
                            <div class="card-actions">
                              <el-button type="danger" size="small" @click.stop="deleteSingleWhitelist(friend)" class="delete-btn"> 删除 </el-button>
                            </div>
                          </div>
                          <div class="selection-indicator">
                            <i class="el-icon-check"></i>
                          </div>
                        </div>
                      </div>

                      <!-- 白名单分页 -->
                      <div class="pagination-container">
                        <Pagination
                          v-model:current-page="whitelistCurrentPage"
                          v-model:page-size="whitelistPageSize"
                          :total="whitelistTotal"
                          @pagination="handleWhitelistPagination"
                        />
                      </div>
                    </div>
                  </div>

                  <!-- 传统好友选择区域（保留兼容性） -->
                  <div class="friend-select-area" v-if="whitelistData.length === 0 && !whitelistQueried">
                    <div class="select-header">
                      <div class="header-info">
                        <span>已选择好友</span>
                        <span class="count-badge">{{ whitelistFriendNames.length }}</span>
                      </div>
                      <el-button type="primary" @click="openFriendSelector('whitelist')" class="friend-select-btn"> 选择好友 </el-button>
                    </div>
                    <div class="friends-content">
                      <div v-if="whitelistFriendNames.length > 0" class="friends-tags">
                        <el-tag
                          v-for="friendName in whitelistFriendNames"
                          :key="friendName"
                          type="success"
                          class="friend-tag"
                          closable
                          @close="removeFriend('whitelist', friendName)"
                        >
                          {{ friendName }}
                        </el-tag>
                      </div>
                      <div v-else class="empty-hint">
                        <div class="hint-icon">👥</div>
                        <div class="hint-text">暂未选择好友，点击上方按钮添加</div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 黑名单配置 -->
        <div class="config-section">
          <div class="section-header">
            <div class="section-title">
              <h2>黑名单配置</h2>
            </div>
          </div>

          <div class="config-grid">
            <div class="config-item friend-select-item">
              <div class="item-label">
                <span class="label-desc">排除选中好友，不进行点赞评论</span>
              </div>
              <div class="item-content">
                <!-- 查询和操作区域 -->
                <div class="blacklist-management">
                  <div class="management-header">
                    <div class="search-area">
                      <el-input v-model="blacklistQuery.labIds" placeholder="标签ID" class="search-input" clearable />
                      <el-input v-model="blacklistQuery.name" placeholder="客户名称" class="search-input" clearable />
                      <el-button type="primary" @click="queryBlacklist" :loading="blacklistLoading" class="search-btn"> 查询 </el-button>
                    </div>
                    <div class="action-area">
                      <el-button type="warning" @click="openFriendSelector('blacklist')" class="add-btn"> 添加好友 </el-button>
                      <el-button type="danger" @click="batchDeleteBlacklist" :disabled="blacklistSelectedIds.length === 0" class="delete-btn">
                        批量删除
                      </el-button>
                    </div>
                  </div>

                  <!-- 黑名单列表 -->
                  <div class="blacklist-cards" v-if="blacklistData.length > 0 || blacklistQueried">
                    <div v-if="blacklistData.length === 0" class="empty-state">
                      <div class="empty-text">暂无黑名单数据</div>
                    </div>
                    <div v-else class="cards-container">
                      <!-- 好友卡片列表 -->
                      <div class="friend-cards-grid">
                        <div
                          v-for="friend in blacklistData"
                          :key="friend.id"
                          class="friend-card blacklist-card"
                          :class="{ selected: blacklistSelectedIds.includes(friend.id.toString()) }"
                          @click="toggleBlacklistSelection(friend)"
                        >
                          <div class="card-content">
                            <div class="friend-avatar-container">
                              <img v-if="friend.customerUrl" :src="friend.customerUrl" class="friend-avatar" @error="handleImageError" />
                              <div v-else class="avatar-placeholder">
                                {{ (friend.customerName || '未知')[0] }}
                              </div>
                            </div>
                            <div class="friend-name">{{ friend.customerName || '未知好友' }}</div>
                            <div class="card-actions">
                              <el-button type="danger" size="small" @click.stop="deleteSingleBlacklist(friend)" class="delete-btn"> 删除 </el-button>
                            </div>
                          </div>
                          <div class="selection-indicator">
                            <i class="el-icon-check"></i>
                          </div>
                        </div>
                      </div>

                      <!-- 黑名单分页 -->
                      <div class="pagination-container">
                        <Pagination
                          v-model:current-page="blacklistCurrentPage"
                          v-model:page-size="blacklistPageSize"
                          :total="blacklistTotal"
                          @pagination="handleBlacklistPagination"
                        />
                      </div>
                    </div>
                  </div>

                  <!-- 传统好友选择区域（保留兼容性） -->
                  <div class="friend-select-area" v-if="blacklistData.length === 0 && !blacklistQueried">
                    <div class="select-header">
                      <div class="header-info">
                        <span>已选择好友</span>
                        <span class="count-badge">{{ blacklistFriendNames.length }}</span>
                      </div>
                      <el-button type="danger" @click="openFriendSelector('blacklist')" class="friend-select-btn"> 选择好友 </el-button>
                    </div>
                    <div class="friends-content">
                      <div v-if="blacklistFriendNames.length > 0" class="friends-tags">
                        <el-tag
                          v-for="friendName in blacklistFriendNames"
                          :key="friendName"
                          type="danger"
                          class="friend-tag"
                          closable
                          @close="removeFriend('blacklist', friendName)"
                        >
                          {{ friendName }}
                        </el-tag>
                      </div>
                      <div v-else class="empty-hint">
                        <div class="hint-icon">🚫</div>
                        <div class="hint-text">暂未选择好友，点击上方按钮添加</div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 保存按钮 -->
        <div class="action-section">
          <div class="save-button-container">
            <el-button @click="submitTask" class="save-button" size="large">
              <div class="button-content">
                <!-- <div class="button-icon">
                <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                  <path
                    d="M9 12L11 14L15 10M21 12C21 16.9706 16.9706 21 12 21C7.02944 21 3 16.9706 3 12C3 7.02944 7.02944 3 12 3C16.9706 3 21 7.02944 21 12Z"
                    stroke="currentColor"
                    stroke-width="2"
                    stroke-linecap="round"
                    stroke-linejoin="round"
                  />
                </svg>
              </div> -->
                <span>应用配置</span>
              </div>
              <div class="button-glow"></div>
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 好友选择弹窗 -->
    <FriendSelectDialog
      v-model="friendSelectorVisible"
      :title="friendSelectorType === 'whitelist' ? '选择白名单好友' : '选择黑名单好友'"
      :multiple="true"
      :selected-friends="currentSelectedFriends"
      @confirm="handleFriendSelectConfirm"
      @cancel="handleFriendSelectCancel"
    />
  </el-config-provider>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { ElMessage } from 'element-plus';
import zhCn from 'element-plus/es/locale/lang/zh-cn';
import {
  getAiGoodCommentsList,
  addOrUpdateAiGoodComments,
  selectAiFriendship,
  addAiFriendship,
  deleteAiFriendship,
  type AiFriendshipResult
} from '@/api/friendSocial/aiThumbsUpReview';
import FriendSelectDialog from '@/components/FriendSelect/FriendSelectDialog.vue';
import Pagination from '@/components/Pagination/index.vue';

// 从本地存储获取wxId
const wxId = ref(JSON.parse(localStorage.getItem('msgprofile') || '{}')?.wx_id || '');

// 规则表单
const taskForm = reactive({
  isGood: 2 as 1 | 2,
  goodIntervalDay: 1,
  goodIntervalTime: 1,
  goodNum: 1,
  goodSum: 1,
  goodRandom: 2,
  isComment: 2 as 1 | 2,
  commentData: '',
  commentIntervalDay: 1,
  commentIntervalTime: 1,
  commentNum: 1,
  commentSum: 1,
  commentRandom: 2,
  isWhitelist: 2 as 1 | 2,
  whitelistFriends: [] as string[],
  isBlacklist: 2 as 1 | 2,
  blacklistFriends: [] as string[]
});

// 好友选择相关
const friendSelectorVisible = ref(false);
const friendSelectorType = ref<'whitelist' | 'blacklist'>('whitelist');

// 存储好友详细信息
const whitelistFriendDetails = ref<any[]>([]);
const blacklistFriendDetails = ref<any[]>([]);

// 白名单管理状态
const whitelistQuery = reactive({
  labIds: '',
  name: ''
});
const whitelistLoading = ref(false);
const whitelistData = ref<AiFriendshipResult[]>([]);
const whitelistQueried = ref(false);
const whitelistSelectedIds = ref<string[]>([]);
const whitelistCurrentPage = ref(1);
const whitelistPageSize = ref(10);
const whitelistTotal = ref(0);

// 黑名单管理状态
const blacklistQuery = reactive({
  labIds: '',
  name: ''
});
const blacklistLoading = ref(false);
const blacklistData = ref<AiFriendshipResult[]>([]);
const blacklistQueried = ref(false);
const blacklistSelectedIds = ref<string[]>([]);
const blacklistCurrentPage = ref(1);
const blacklistPageSize = ref(10);
const blacklistTotal = ref(0);

// 当前选中的好友列表（用于传递给FriendSelectDialog）
const currentSelectedFriends = ref<string[]>([]);

// 白名单好友名字列表
const whitelistFriendNames = computed(() => {
  return whitelistFriendDetails.value.map((friend) => friend.userName || friend.nick_name || '未知好友');
});

// 黑名单好友名字列表
const blacklistFriendNames = computed(() => {
  return blacklistFriendDetails.value.map((friend) => friend.userName || friend.nick_name || '未知好友');
});

// 打开好友选择器
const openFriendSelector = (type: 'whitelist' | 'blacklist') => {
  friendSelectorType.value = type;
  // 清空之前的选中状态
  if (type === 'whitelist') {
    whitelistSelectedIds.value = [];
  } else {
    blacklistSelectedIds.value = [];
  }
  // 清空好友选择器的选中状态，确保所有好友都恢复为未选中
  currentSelectedFriends.value = [];
  friendSelectorVisible.value = true;
};

// 处理好友选择确认
const handleFriendSelectConfirm = async (selectedFriends: any[]) => {
  const friendIds = selectedFriends.map((friend) => friend.wxAccount);

  if (friendSelectorType.value === 'whitelist') {
    taskForm.whitelistFriends = friendIds;
    whitelistFriendDetails.value = selectedFriends;

    // 调用新增白名单API
    if (friendIds.length > 0) {
      await addFriendsToList(0, friendIds);
      // 刷新白名单数据
      queryWhitelist();
    }
  } else {
    taskForm.blacklistFriends = friendIds;
    blacklistFriendDetails.value = selectedFriends;

    // 调用新增黑名单API
    if (friendIds.length > 0) {
      await addFriendsToList(1, friendIds);
      // 刷新黑名单数据
      queryBlacklist();
    }
  }
};

// 处理好友选择取消
const handleFriendSelectCancel = () => {
  friendSelectorVisible.value = false;
};

// 移除好友
const removeFriend = (type: 'whitelist' | 'blacklist', friendName: string) => {
  if (type === 'whitelist') {
    const index = whitelistFriendDetails.value.findIndex((friend) => (friend.userName || friend.nick_name || '未知好友') === friendName);
    if (index > -1) {
      whitelistFriendDetails.value.splice(index, 1);
      taskForm.whitelistFriends.splice(index, 1);
    }
  } else {
    const index = blacklistFriendDetails.value.findIndex((friend) => (friend.userName || friend.nick_name || '未知好友') === friendName);
    if (index > -1) {
      blacklistFriendDetails.value.splice(index, 1);
      taskForm.blacklistFriends.splice(index, 1);
    }
  }
};

// 加载数据
const loadData = async () => {
  try {
    const res = await getAiGoodCommentsList(wxId.value);
    if (res.code === 200 && res.data && res.data.length > 0) {
      const backendData = res.data[0];
      // 直接更新表单数据
      taskForm.isGood = Number(backendData.is_good) as 1 | 2;
      taskForm.goodIntervalDay = backendData.good_interval_day;
      taskForm.goodIntervalTime = backendData.good_interval_time;
      taskForm.goodNum = backendData.good_num;
      taskForm.goodSum = backendData.good_sum;
      taskForm.goodRandom = Number(backendData.good_random) as 1 | 2;
      taskForm.isComment = Number(backendData.is_comment) as 1 | 2;
      taskForm.commentData = backendData.comment_data || '';
      taskForm.commentIntervalDay = backendData.comment_interval_day;
      taskForm.commentIntervalTime = backendData.comment_interval_time;
      taskForm.commentNum = backendData.comment_num;
      taskForm.commentSum = backendData.comment_sum;
      taskForm.commentRandom = Number(backendData.comment_random) as 1 | 2;

      // 处理白名单和黑名单数据
      taskForm.isWhitelist = Number((backendData as any).is_whitelist || 2) as 1 | 2;
      taskForm.whitelistFriends = (backendData as any).whitelist_friends ? JSON.parse((backendData as any).whitelist_friends) : [];
      taskForm.isBlacklist = Number((backendData as any).is_blacklist || 2) as 1 | 2;
      taskForm.blacklistFriends = (backendData as any).blacklist_friends ? JSON.parse((backendData as any).blacklist_friends) : [];
    } else {
      ElMessage.error(res.msg || '获取数据失败');
    }
  } catch (error) {
    console.error('获取数据失败:', error);
    ElMessage.error('获取数据失败');
  }
};

// 提交规则
const submitTask = async () => {
  try {
    const res = await addOrUpdateAiGoodComments({
      wxId: wxId.value,
      isGood: taskForm.isGood,
      goodIntervalDay: taskForm.goodIntervalDay,
      goodIntervalTime: taskForm.goodIntervalTime,
      goodNum: taskForm.goodNum,
      goodSum: taskForm.goodSum,
      goodRandom: taskForm.goodRandom,
      isComment: taskForm.isComment,
      commentData: taskForm.commentData,
      commentIntervalDay: taskForm.commentIntervalDay,
      commentIntervalTime: taskForm.commentIntervalTime,
      commentNum: taskForm.commentNum,
      commentSum: taskForm.commentSum,
      commentRandom: taskForm.commentRandom,
      ...({
        isWhitelist: taskForm.isWhitelist,
        whitelistFriends: JSON.stringify(taskForm.whitelistFriends),
        isBlacklist: taskForm.isBlacklist,
        blacklistFriends: JSON.stringify(taskForm.blacklistFriends)
      } as any)
    });
    if (res.code === 200) {
      ElMessage.success('保存成功');
      loadData(); // 重新加载数据
    } else {
      ElMessage.error(res.msg || '保存失败');
    }
  } catch (error) {
    console.error('保存失败:', error);
    ElMessage.error('保存失败');
  }
};

// 添加好友到黑白名单
const addFriendsToList = async (type: 0 | 1, customerWxIds: string[]) => {
  try {
    const res = await addAiFriendship({
      wxId: wxId.value,
      type,
      customerWxIds: customerWxIds.join(',')
    });

    if (res.code === 200) {
      ElMessage.success(`成功添加到${type === 0 ? '白名单' : '黑名单'}`);
    } else {
      ElMessage.error(res.msg || '添加失败');
    }
  } catch (error) {
    console.error('添加失败:', error);
    ElMessage.error('添加失败');
  }
};

// 查询白名单
const queryWhitelist = async (showMessage = true) => {
  if (!wxId.value) {
    if (showMessage) {
      ElMessage.error('微信ID不能为空');
    }
    return;
  }

  whitelistLoading.value = true;
  whitelistQueried.value = true;

  try {
    const params = {
      wxId: wxId.value,
      type: 0 as 0 | 1,
      current: whitelistCurrentPage.value,
      size: whitelistPageSize.value,
      ...(whitelistQuery.labIds && { labIds: whitelistQuery.labIds }),
      ...(whitelistQuery.name && { name: whitelistQuery.name })
    };

    const res = await selectAiFriendship(params);

    if (res.code === 200) {
      whitelistData.value = res.data?.records || [];
      whitelistTotal.value = res.data?.total || 0;
    } else {
      if (showMessage) {
        ElMessage.error(res.msg || '查询失败');
      }
      whitelistData.value = [];
      whitelistTotal.value = 0;
    }
  } catch (error) {
    console.error('查询失败:', error);
    if (showMessage) {
      ElMessage.error('查询失败');
    }
    whitelistData.value = [];
    whitelistTotal.value = 0;
  } finally {
    whitelistLoading.value = false;
  }
};

// 查询黑名单
const queryBlacklist = async (showMessage = true) => {
  if (!wxId.value) {
    if (showMessage) {
      ElMessage.error('微信ID不能为空');
    }
    return;
  }

  blacklistLoading.value = true;
  blacklistQueried.value = true;

  try {
    const params = {
      wxId: wxId.value,
      type: 1 as 0 | 1,
      current: blacklistCurrentPage.value,
      size: blacklistPageSize.value,
      ...(blacklistQuery.labIds && { labIds: blacklistQuery.labIds }),
      ...(blacklistQuery.name && { name: blacklistQuery.name })
    };

    const res = await selectAiFriendship(params);

    if (res.code === 200) {
      blacklistData.value = res.data?.records || [];
      blacklistTotal.value = res.data?.total || 0;
    } else {
      if (showMessage) {
        ElMessage.error(res.msg || '查询失败');
      }
      blacklistData.value = [];
      blacklistTotal.value = 0;
    }
  } catch (error) {
    console.error('查询失败:', error);
    if (showMessage) {
      ElMessage.error('查询失败');
    }
    blacklistData.value = [];
    blacklistTotal.value = 0;
  } finally {
    blacklistLoading.value = false;
  }
};

// 切换白名单选择
const toggleWhitelistSelection = (friend: AiFriendshipResult) => {
  const friendId = friend.id.toString();
  const index = whitelistSelectedIds.value.indexOf(friendId);
  if (index > -1) {
    whitelistSelectedIds.value.splice(index, 1);
  } else {
    whitelistSelectedIds.value.push(friendId);
  }
};

// 切换黑名单选择
const toggleBlacklistSelection = (friend: AiFriendshipResult) => {
  const friendId = friend.id.toString();
  const index = blacklistSelectedIds.value.indexOf(friendId);
  if (index > -1) {
    blacklistSelectedIds.value.splice(index, 1);
  } else {
    blacklistSelectedIds.value.push(friendId);
  }
};

// 处理图片加载错误
const handleImageError = (event: Event) => {
  const img = event.target as HTMLImageElement;
  img.style.display = 'none';
};

// 批量删除白名单
const batchDeleteWhitelist = async () => {
  if (whitelistSelectedIds.value.length === 0) {
    ElMessage.warning('请选择要删除的数据');
    return;
  }

  try {
    const res = await deleteAiFriendship({
      ids: whitelistSelectedIds.value.join(',')
    });

    if (res.code === 200) {
      ElMessage.success('删除成功');
      whitelistSelectedIds.value = [];
      queryWhitelist(false); // 刷新数据
    } else {
      ElMessage.error(res.msg || '删除失败');
    }
  } catch (error) {
    console.error('删除失败:', error);
    ElMessage.error('删除失败');
  }
};

// 批量删除黑名单
const batchDeleteBlacklist = async () => {
  if (blacklistSelectedIds.value.length === 0) {
    ElMessage.warning('请选择要删除的数据');
    return;
  }

  try {
    const res = await deleteAiFriendship({
      ids: blacklistSelectedIds.value.join(',')
    });

    if (res.code === 200) {
      ElMessage.success('删除成功');
      blacklistSelectedIds.value = [];
      queryBlacklist(false); // 刷新数据
    } else {
      ElMessage.error(res.msg || '删除失败');
    }
  } catch (error) {
    console.error('删除失败:', error);
    ElMessage.error('删除失败');
  }
};

// 删除单个白名单
const deleteSingleWhitelist = async (row: AiFriendshipResult) => {
  try {
    const res = await deleteAiFriendship({
      ids: row.id.toString()
    });

    if (res.code === 200) {
      ElMessage.success('删除成功');
      queryWhitelist(false); // 刷新数据
    } else {
      ElMessage.error(res.msg || '删除失败');
    }
  } catch (error) {
    console.error('删除失败:', error);
    ElMessage.error('删除失败');
  }
};

// 删除单个黑名单
const deleteSingleBlacklist = async (row: AiFriendshipResult) => {
  try {
    const res = await deleteAiFriendship({
      ids: row.id.toString()
    });

    if (res.code === 200) {
      ElMessage.success('删除成功');
      queryBlacklist(false); // 刷新数据
    } else {
      ElMessage.error(res.msg || '删除失败');
    }
  } catch (error) {
    console.error('删除失败:', error);
    ElMessage.error('删除失败');
  }
};

// 白名单分页处理
const handleWhitelistPagination = ({ pageNum, pageSize }: { pageNum: number; pageSize: number }) => {
  whitelistCurrentPage.value = pageNum;
  whitelistPageSize.value = pageSize;
  queryWhitelist(false);
};

// 黑名单分页处理
const handleBlacklistPagination = ({ pageNum, pageSize }: { pageNum: number; pageSize: number }) => {
  blacklistCurrentPage.value = pageNum;
  blacklistPageSize.value = pageSize;
  queryBlacklist(false);
};

onMounted(() => {
  loadData();
  // 默认加载白名单和黑名单数据，不显示消息提示
  queryWhitelist(false);
  queryBlacklist(false);
});
</script>

<style lang="scss" scoped>
.ai-thumbs-up-review {
  min-height: 100vh;
  background: linear-gradient(135deg, #f8fafc 0%, #e5e7eb 100%);
  position: relative;
  overflow: hidden;

  .animated-background {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    pointer-events: none;
    z-index: 1;

    .floating-particles {
      position: absolute;
      width: 4px;
      height: 4px;
      background: #667eea;
      border-radius: 50%;
      animation: float 6s ease-in-out infinite;
      opacity: 0.4;

      &:nth-child(1) {
        top: 20%;
        left: 10%;
        animation-delay: 0s;
        background: #667eea;
      }

      &:nth-child(2) {
        top: 60%;
        right: 15%;
        animation-delay: 2s;
        background: #764ba2;
      }

      &:nth-child(3) {
        bottom: 30%;
        left: 20%;
        animation-delay: 4s;
        background: #f59e0b;
      }
    }
  }

  .config-container {
    position: relative;
    z-index: 2;
    max-width: 1300px;
    margin: 0 auto;
    padding: 80px 20px 40px;

    .config-section {
      background: rgba(255, 255, 255, 0.95);
      backdrop-filter: blur(10px);
      border: 1px solid #e5e7eb;
      border-radius: 24px;
      padding: 25px;
      margin-bottom: 30px;
      transition: all 0.3s ease;
      box-shadow: 0 8px 32px rgba(102, 126, 234, 0.08);

      &:hover {
        border-color: #667eea;
        box-shadow: 0 8px 32px rgba(102, 126, 234, 0.15);
      }

      .section-header {
        display: flex;
        align-items: center;
        gap: 20px;
        margin-bottom: 32px;
        padding-bottom: 20px;
        border-bottom: 1px solid #e5e7eb;

        .section-icon {
          width: 56px;
          height: 56px;
          background: linear-gradient(135deg, #667eea, #764ba2);
          border-radius: 16px;
          display: flex;
          align-items: center;
          justify-content: center;
          color: #fff;
          font-size: 24px;
        }

        .section-title {
          flex: 1;

          h2 {
            margin: 0;
            font-size: 22px;
            font-weight: 700;
            color: #1f2937;
          }

          p {
            margin: 4px 0 0 0;
            color: #6b7280;
            font-size: 14px;
          }
        }
      }

      .config-grid {
        display: grid;
        grid-template-columns: repeat(5, 1fr);
        gap: 16px;

        &.disabled {
          opacity: 0.5;
          pointer-events: none;
        }

        .config-item {
          background: #f8fafc;
          border: 1px solid #e5e7eb;
          border-radius: 12px;
          padding: 16px;
          transition: all 0.3s ease;

          &:hover {
            border-color: #667eea;
            background: #eef2ff;
          }

          .item-label {
            margin-bottom: 12px;

            .label-text {
              display: block;
              font-size: 14px;
              font-weight: 600;
              color: #1f2937;
              margin-bottom: 2px;
            }

            .label-desc {
              display: block;
              font-size: 12px;
              color: #6b7280;
            }
          }

          .item-input {
            display: flex;
            align-items: center;
            gap: 12px;

            .tech-input {
              flex: 1;

              :deep(.el-input__wrapper) {
                background: #fff;
                border: 1px solid #e5e7eb;
                border-radius: 12px;
                box-shadow: none;
                transition: all 0.3s ease;

                &:hover {
                  border-color: #667eea;
                }

                &.is-focus {
                  border-color: #764ba2;
                  box-shadow: 0 0 0 3px rgba(118, 75, 162, 0.08);
                }

                .el-input__inner {
                  color: #1f2937;
                  font-weight: 500;

                  &::placeholder {
                    color: #9ca3af;
                  }
                }
              }

              :deep(.el-input-number__decrease),
              :deep(.el-input-number__increase) {
                background: #f1f5f9;
                border: none;
                color: #667eea;
                transition: all 0.3s ease;

                &:hover {
                  background: #e0e7ff;
                  color: #764ba2;
                }
              }
            }

            .unit {
              color: #6b7280;
              font-size: 14px;
              font-weight: 500;
              min-width: 30px;
            }
          }
        }
      }
    }

    .action-section {
      display: flex;
      justify-content: center;
      margin-top: 40px;

      .save-button-container {
        position: relative;

        .save-button {
          position: relative;
          background: linear-gradient(135deg, #667eea, #764ba2);
          border: none;
          padding: 16px 48px;
          border-radius: 16px;
          color: #fff;
          font-weight: 700;
          font-size: 18px;
          cursor: pointer;
          overflow: hidden;
          transition: all 0.3s ease;
          box-shadow: 0 8px 32px rgba(102, 126, 234, 0.15);

          &:hover {
            transform: translateY(-2px);
            box-shadow: 0 12px 40px rgba(102, 126, 234, 0.22);

            .button-glow {
              opacity: 1;
            }
          }

          .button-content {
            display: flex;
            align-items: center;
            gap: 12px;
            position: relative;
            z-index: 2;

            .button-icon {
              width: 24px;
              height: 24px;
            }
          }

          .button-glow {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: linear-gradient(135deg, #667eea, #764ba2);
            border-radius: 16px;
            opacity: 0;
            transition: opacity 0.3s ease;
            z-index: 1;
          }
        }
      }
    }
  }
}

// 动画
@keyframes float {
  0%,
  100% {
    transform: translateY(0px) rotate(0deg);
  }
  50% {
    transform: translateY(-20px) rotate(180deg);
  }
}

@keyframes pulse {
  0%,
  100% {
    opacity: 0.5;
    transform: scale(1);
  }
  50% {
    opacity: 0.8;
    transform: scale(1.05);
  }
}

// 响应式设计
@media (max-width: 1400px) {
  .config-grid {
    grid-template-columns: repeat(4, 1fr);
  }
}
@media (max-width: 1200px) {
  .config-grid {
    grid-template-columns: repeat(3, 1fr);
  }
}
@media (max-width: 900px) {
  .config-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}
@media (max-width: 600px) {
  .config-grid {
    grid-template-columns: 1fr;
  }
}

// 自定义滚动条
::-webkit-scrollbar {
  width: 8px;
}

::-webkit-scrollbar-track {
  background: #f1f5f9;
}

::-webkit-scrollbar-thumb {
  background: linear-gradient(135deg, #667eea, #764ba2);
  border-radius: 4px;
}

::-webkit-scrollbar-thumb:hover {
  background: linear-gradient(135deg, #5a67d8, #6b46c1);
}

// 好友选择项样式
.friend-select-item {
  grid-column: 1 / -1; // 占满整行

  .item-label {
    margin-bottom: 12px;
  }

  .item-content {
    width: 100%;
  }

  .friend-select-area {
    background: #ffffff;
    border: 1px solid #e5e7eb;
    border-radius: 8px;
    padding: 16px;
    min-height: 80px;

    .select-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 12px;
      padding-bottom: 8px;
      border-bottom: 1px solid #f5f5f5;

      .header-info {
        display: flex;
        align-items: center;
        gap: 6px;
        font-size: 14px;
        color: #666;

        .count-badge {
          background: #409eff;
          color: white;
          padding: 1px 6px;
          border-radius: 10px;
          font-size: 12px;
          min-width: 18px;
          text-align: center;
        }
      }

      .friend-select-btn {
        border-radius: 4px;
        font-size: 14px;
        padding: 6px 12px;

        .el-icon {
          font-size: 14px;
        }
      }
    }

    .friends-content {
      min-height: 40px;
      display: flex;
      align-items: center;
    }

    .friends-tags {
      display: flex;
      flex-wrap: wrap;
      gap: 6px;
      width: 100%;

      .friend-tag {
        font-size: 12px;
        padding: 4px 8px;
        border-radius: 4px;

        :deep(.el-tag__close) {
          margin-left: 4px;
          font-size: 10px;
        }
      }
    }

    .empty-hint {
      font-size: 13px;
      color: #999;
      text-align: center;
      padding: 16px;
      border: 1px dashed #ddd;
      border-radius: 4px;
      background: #fafafa;
      width: 100%;
      display: flex;
      flex-direction: column;
      align-items: center;
      gap: 4px;

      .hint-icon {
        font-size: 16px;
        opacity: 0.6;
      }

      .hint-text {
        font-size: 12px;
      }
    }
  }
}

// 黑白名单管理样式
.whitelist-management,
.blacklist-management {
  .management-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 20px;
    margin-bottom: 20px;
    padding: 20px;
    background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
    border: 1px solid #e2e8f0;
    border-radius: 12px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);

    .search-area {
      display: flex;
      align-items: center;
      gap: 12px;
      flex: 1;

      .search-input {
        width: 160px;

        :deep(.el-input__wrapper) {
          background: #fff;
          border: 1px solid #d1d5db;
          border-radius: 8px;
          transition: all 0.3s ease;
          box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);

          &:hover {
            border-color: #667eea;
            box-shadow: 0 1px 6px rgba(102, 126, 234, 0.15);
          }

          &.is-focus {
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
          }
        }
      }

      .search-btn {
        background: linear-gradient(135deg, #667eea, #764ba2);
        border: none;
        border-radius: 8px;
        font-size: 14px;
        font-weight: 500;
        padding: 10px 20px;
        color: white;
        transition: all 0.3s ease;

        &:hover {
          background: linear-gradient(135deg, #5a67d8, #6b46c1);
          transform: translateY(-1px);
          box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
        }
      }
    }

    .action-area {
      display: flex;
      align-items: center;
      gap: 12px;

      .add-btn {
        border-radius: 8px;
        font-size: 14px;
        font-weight: 500;
        padding: 10px 20px;
        transition: all 0.3s ease;

        &:hover {
          transform: translateY(-1px);
          box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        }
      }

      .delete-btn {
        border-radius: 8px;
        font-size: 14px;
        font-weight: 500;
        padding: 10px 20px;
        transition: all 0.3s ease;

        &:hover {
          transform: translateY(-1px);
          box-shadow: 0 4px 12px rgba(239, 68, 68, 0.3);
        }
      }
    }
  }

  .whitelist-cards,
  .blacklist-cards {
    background-color: #fff;
    border-radius: 12px;
    padding: 20px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
    border: 1px solid #e2e8f0;

    .empty-state {
      text-align: center;
      padding: 60px 20px;
      background: #fff;

      .empty-icon {
        font-size: 48px;
        margin-bottom: 16px;
        opacity: 0.5;
      }

      .empty-text {
        font-size: 16px;
        font-weight: 500;
        color: #6b7280;
      }
    }

    .cards-container {
      .friend-cards-grid {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
        gap: 16px;
        margin-bottom: 20px;

        .friend-card {
          position: relative;
          background: #fff;
          border: 2px solid #e5e7eb;
          border-radius: 12px;
          padding: 16px;
          cursor: pointer;
          transition: all 0.3s ease;
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);

          &:hover {
            border-color: #667eea;
            box-shadow: 0 4px 16px rgba(102, 126, 234, 0.15);
            transform: translateY(-2px);
          }

          &.selected {
            border-color: #52c41a;
            background: linear-gradient(135deg, #f6ffed 0%, #f0f9ff 100%);
            box-shadow: 0 4px 16px rgba(82, 196, 26, 0.2);

            .selection-indicator {
              opacity: 1;
              transform: scale(1);
            }
          }

          &.blacklist-card.selected {
            border-color: #ff4d4f;
            background: linear-gradient(135deg, #fff2f0 0%, #fff1f0 100%);
            box-shadow: 0 4px 16px rgba(255, 77, 79, 0.2);
          }

          .card-content {
            display: flex;
            flex-direction: column;
            align-items: center;
            text-align: center;

            .friend-avatar-container {
              margin-bottom: 12px;

              .friend-avatar {
                width: 60px;
                height: 60px;
                border-radius: 50%;
                object-fit: cover;
                border: 3px solid #e5e7eb;
                transition: all 0.3s ease;
              }

              .avatar-placeholder {
                width: 60px;
                height: 60px;
                border-radius: 50%;
                background: linear-gradient(135deg, #667eea, #764ba2);
                color: white;
                display: flex;
                align-items: center;
                justify-content: center;
                font-size: 24px;
                font-weight: 600;
                border: 3px solid #e5e7eb;
              }
            }

            .friend-name {
              font-size: 14px;
              font-weight: 600;
              color: #1f2937;
              margin-bottom: 12px;
              line-height: 1.4;
              max-width: 100%;
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
            }

            .card-actions {
              .delete-btn {
                font-size: 12px;
                padding: 4px 12px;
                border-radius: 6px;
                transition: all 0.2s ease;

                &:hover {
                  transform: translateY(-1px);
                  box-shadow: 0 2px 8px rgba(239, 68, 68, 0.3);
                }
              }
            }
          }

          .selection-indicator {
            position: absolute;
            top: 8px;
            right: 8px;
            width: 24px;
            height: 24px;
            background: #52c41a;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 14px;
            opacity: 0;
            transform: scale(0.8);
            transition: all 0.3s ease;
          }
        }
      }
    }

    .pagination-container {
      margin-top: 20px;
      display: flex;
      justify-content: center;
    }
  }
}

// 响应式适配
@media (max-width: 768px) {
  .whitelist-management,
  .blacklist-management {
    .management-header {
      flex-direction: column;
      align-items: stretch;
      gap: 12px;

      .search-area {
        flex-direction: column;
        align-items: stretch;

        .search-input {
          width: 100%;
        }
      }

      .action-area {
        justify-content: center;
      }
    }

    .friend-cards-grid {
      grid-template-columns: repeat(auto-fill, minmax(160px, 1fr)) !important;
      gap: 12px !important;

      .friend-card {
        padding: 12px !important;

        .card-content {
          .friend-avatar-container {
            margin-bottom: 8px !important;

            .friend-avatar,
            .avatar-placeholder {
              width: 50px !important;
              height: 50px !important;
            }

            .avatar-placeholder {
              font-size: 20px !important;
            }
          }

          .friend-name {
            font-size: 13px !important;
            margin-bottom: 8px !important;
          }

          .card-actions {
            .delete-btn {
              font-size: 11px !important;
              padding: 3px 8px !important;
            }
          }
        }

        .selection-indicator {
          width: 20px !important;
          height: 20px !important;
          font-size: 12px !important;
        }
      }
    }

    .batch-toolbar {
      flex-direction: column !important;
      gap: 8px !important;
      text-align: center !important;
    }
  }
}
</style>
